<?php
declare (strict_types = 1);
namespace app\shop\model;
use app\api\model\IdentityCard;
use app\common\model\BaseModel;
use app\mall\model\Goods;
use think\Model;

use think\Db;

Class ShopCoupon extends BaseModel
{
    // 查看列表信息
    public function getList($user,$get){
        // 拿取店铺信息
        $shopModel = new  ShopUsers();
        $shopList = $shopModel->regShop($user->id);
        if(!$shopList['flag']) return retu_json(400,$shopList['msg']);
        $shopUser = $shopList['data'];
        $time = time();
        $this->queryList($get,'status,total_amount,amount,related_id,total,day,add_time,start_time,end_time,apply_num,use_num',['is_delete'=>0,'shop_id'=>$shopUser->id],'add_time desc');
        foreach($this->list['data'] as &$item){
            $item['name'] = $shopUser['name'];
            $item['expired_true'] = $item['end_time'] < time();
            $item['goods_num'] = $item['related_id'] && strlen($item['related_id']) > 1 ? count(explode(',',$item['related_id'])) : 0;
        }
    }


    /**
     *  店家创建优惠券
     */
    public function createCoupon($user,$params,$self){
        // 拿取参数
        list($status,$related_id,$total_amount,$amount,$total,$start_time,$end_time,$name) = $self->getSetDefaultParams('status|0,related_id| ,total_amount|0,amount|0,total|0,start_time|,end_time|,name|');
        // 如果类型为 2 则必须有指定商品id
        if($status == 2 && !$related_id)return retu_json(400,'指定商品必须填写');
        // 如果使用条件为 满减1 判断是否有满减抵扣 且 满减抵扣金额小于1 
        // 拿取店铺信息
        $shopModel = new  ShopUsers();
        $shopList = $shopModel->regShop($user->id);
        if(!$shopList['flag']) return retu_json(400,$shopList['msg']);
        $shopUser = $shopList['data'];
        //如果有满多少减 优惠券面额 需要小于满抵扣门槛
        if($total_amount >  0 && $amount > $total_amount)return retu_json(400,'当前有门槛，满抵扣金额需要大于优惠券面额');
        $time = time();
        $startTime = strtotime($start_time.' 00:00:00');
        // 限制 大于当前时间
        if($time < $startTime) return retu_json(400,'优惠券开始时间必须为今天');
        // 限制结束时间大于开始时间
        $endTime = strtotime($end_time.' 23:59:59');
        if($endTime <$startTime)return retu_json(400,'优惠券结束时间必须大于开始时间');
        // 优惠券天数限制 如果超过30天
        if(($endTime - $startTime) / 3600 / 24 > 31) return retu_json(400,'优惠券有效期最多为30天');
        $cha = date_diff(date_create(date('Ymd',(int)$start_time)),date_create(date('Ymd',(int)$end_time)));
        $data = [
            'shop_id' => $shopUser->id - 0,
            'code' => md5(uniqid((string)microtime(true),true)),
            'status' => $status,
            'related_id' => $related_id,
            'total_amount' => $total_amount, // 为0表示 无限制 ，  否则为满减
            'amount' => $amount,
            'total' => $total,
            'start_time' => $startTime,
            'end_time' => $endTime,
            'add_time' => $time,
            'day' => $cha->days,
            'name' => $name
        ];
        $flag = $this::create($data);
        if(!$flag) return retu_json(400,'错误，麻烦重新尝试');
        return retu_json(200 ,'创建成功');
    }

    /**
     * 是否可以使用优惠券
     */
    public function getCouponLimit($oneGoods){
        // 如果没有该店铺
        if($oneGoods->shop_id <= 0){
            $list['msg'] = '此商品没有该店铺';
            return $list;
        }
        $where = [
            ['shop_id','=',$oneGoods->shop_id],
            ['end_time','>',time()],
            ['apply_status','=',1],
            ['is_delete','=',0],
        ];
        // 优惠券拿取
        return ShopCoupon::where($where)->count();
    }

    /**
     * 根据商品获取 到 对应的优惠券列表
     * @param $user 用户信息 ,如果有用户信息 则进行判断已领取的优惠券
     */
    public function getCouponList($param,$user = null,$oneGoods = null){
        // 如果没有该商品
        if(!$oneGoods){
            $id =  isset($param['id']) ? $param['id'] : 0;
            $list = [
                'bool' => false,
                'msg' => '商品序号为空',
                'data'=> []
            ];
            if(!$id || $id <= 0){
                return $list;
            }
            // 商品记录
            if(!$oneGoods = Goods::find($id)){
                $list['msg'] = '商品没有该记录';
                return $list;
            }
            // 如果下架
            if($oneGoods->status != 1){
                $list['msg'] = '商品已下架';
                return $list;
            }
            // 如果删除
            if($oneGoods->is_delete != 0){
                $list['msg'] = '商品已被清空';
                return $list;
            }
            // 如果没有该店铺
            if($oneGoods->shop_id <= 0){
                $list['msg'] = '此商品没有该店铺';
                return $list;
            }
        }
        $where = [
            ['shop_id','=',$oneGoods->shop_id],
            ['end_time','>',time()],
            ['apply_status','=',1],
            ['is_delete','=',0],
        ];
        // 优惠券拿取
        $list['data'] = ShopCoupon::where($where)->field('id,status,total_amount,amount,total,start_time,end_time')->select();
        if($list['data'] && count($list['data']) > 0){
            foreach($list['data'] as &$item){
                // 当前用户对应优惠券状态  0 表示可以 领取 
                $item['apply_status'] = 0;
                if($user && UserCoupon::where(['coupon_id' => $item->id,'uid'=> $user->id])->count() > 0){
                    $item['apply_status'] = 1;
                    unset($item['getUserCouponOne']);
                }
            }
        }
        $list['bool'] = true;
        $list['msg'] = '拿取优惠券列表成功';
        return $list;
    }

    /**
     * 判断该商品是否在此商家优惠券使用范围内
     */
    public function getRegGoods($goodsId,$userCoupon){
        $bool = false;
        if($shopCoupon = ShopCoupon::find($userCoupon['coupon_id'])){
            if($shopCoupon->related_id){
                $arrs = explode(',',$shopCoupon->related_id);
                $bool = count($arrs) > 0 && in_array($goodsId,$arrs);
            }
        }
        return $bool;
    }



    /**
     * 获取到对应的用户优惠券
     */
    public function getUserCouponOne(){
        return $this::hasOne(UserCoupon::class,'coupon_id','id');
    }
}